/**
 * @class Kohive.app.UsersController
 * @extends ExtMVC.Controller
 * Manages the kohive Users
 */
Kohive.app.UsersController = Ext.extend(Kohive.controllers.KohiveController, {
	name		: 'users',

	constructor	: function() {
		Kohive.app.UsersController.superclass.constructor.call(this, {
					viewsPackage	: Kohive.views.users
				});

		this.initEvents();
	},

	/**
	 * @action update
	 * Updates the given user with the provided arguments
	 * @param {Kohive.models.User} user The user instance which needs to be updated
	 * @param {Object} fields The fields to be updated on the user
	 */
	update		: function(user, fields, opts) {
		this.fireEvent('before-update');

		for (var key in fields) {
			user.set(key, fields[key]);
		};

		user.save(Ext.applyIf(opts || {}, {
					url		: '/update_user',
					scope	: this,
					success	: function() {
						this.fireEvent('update', user);
					},
					failure	: function(model) {
						this.fireEvent('update-failed', user, model);
					}
				}));
	},

	/**
	 * @action destroy 
	 * Destroys the passed user and fires a user-destroyed event
	 * @param {Kohive.models.User} user The user to destroy
	 */
	destroy		: function(user) {
		user.destroy({
					url		: '/leave',
					success	: function() {
						return Ext.Msg.show({
									title	: '',
									msg		: Ext.ux.Translator
											.translate('destroy_account_goodbye_desc')
								}
						);
					},
					failure	: function() {
						return Ext.Msg.show({
									title	: '',
									msg		: Ext.ux.Translator
											.translate('destroy_account_error_desc'),
									buttons	: {
										no	: Ext.ux.Translator
												.translate('cancel')
									}
								}
						);
					}
				}
		);
	},

	/**
	 * TODO: A hacky method to prepend the /memberships/:membership_id/ segment to the front of an AJAX
	 * request url.  This really ought to be handled by the model, so factor it out of here when possible
	 * @param {String} url The url to append to the memberships scope
	 * @return {String} The fully scoped url
	 */
	scopedUrl	: function(url) {
		return String.format("/memberships/{0}/{1}", Kohive.OS.getCurrentHive()
						.get('id'), url);
	},

	/**
	 * Sets up all of the events this controller emits
	 */
	initEvents	: function() {
		this.addEvents(
				/**
		 * @event before-update
		 * Fired before an user update request is sent
		 */
				'before-update',

				/**
				 * @event update
				 * Fired when an user has been successful updated
				 * @param {Kohive.models.User} user The user that was updated
				 */
				'update',

				/**
				 * @event update-failed
				 * Fired when the update fails
				 */
				'update-failed',

				/**
				 * @event user-destroyed
				 * Fires when a user has been destroyed
				 */
				'user-destroyed'
		);
	}

}
);

Kohive.OS.registerController('users', Kohive.app.UsersController);